package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHUtil;
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat;

/**
 *
 * @Title: apiSyncMailResult
 * @Description:知决邮件发送结果通知过河兵
 *
 */

public class apiSyncMailResult implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSyncMailResult.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();
        JSONArray resultArr = new JSONArray();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        // 进行签名验证
        JSONObject signJson = signUtil.CheckSign(JSONObject.parseObject(inData, Feature.OrderedField));
        log.info("[签名验证结果]:");
        log.info(signJson);

        // 如果签名检查后有返回值则签名失败返回签名结果
        if (signJson != null && 1 == 2) {
            return signJson.toString();
        } else {
            try {
                //解析Json
                JSONObject inJson = JSONObject.parseObject(inData, Feature.OrderedField);
                JSONArray inJsonData = inJson.getJSONArray("data");

                JSONObject inJsonDataP = new JSONObject();

                // 版本号
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
                String timeInfo = sdf.format(System.currentTimeMillis());
                String Batch_Id = "v-" + timeInfo + "-" + KHUtil.getRandomString(6).toUpperCase();

                for (int i = 0; i < inJsonData.size(); i++) {
                    // 清空标识变量
                    int deal_code = 0;
                    String deal_msg = "";

                    // 获取当前对象
                    inJsonDataP = inJsonData.getJSONObject(i);
                    log.debug("[" + i + "]" + "当前处理数据：" + inJsonDataP.toString());

                    String user_id = inJsonDataP.getString("user_id");
                    String email_plan_id = inJsonDataP.getString("email_plan_id");
                    String email_plan_desc = inJsonDataP.getString("email_plan_desc");
                    String email_send_time = inJsonDataP.getString("email_send_time");
                    String deal_flag = inJsonDataP.getString("deal_flag");
                    log.debug("[" + i + "]" + "当前推送数据解析 user_id：" + user_id + " email_plan_id：" + email_plan_id + " email_plan_desc：" + email_plan_desc + " email_send_time：" + email_send_time + " deal_flag：" + deal_flag);

                    // 记录调用历史
                    int mailresult = eliteBean.update("insert into hst_mailresult_log(mailResultguid,user_id,email_plan_id,email_plan_desc,email_send_time,deal_flag,Batch_Id) values(UUID(),'" + user_id + "','" + email_plan_id + "','" + email_plan_desc + "','" + email_send_time + "','" + deal_flag + "','" + Batch_Id + "')", "dataSource");
                    log.debug("更新结果:" + mailresult.toString());

                    try {
                        // 2-知悉并跟进
                        if (deal_flag == "3") {
                            mailresult = eliteBean.update("insert into hst_mailresult(mailResultguid,user_id,email_plan_id,email_plan_desc,email_send_time,deal_flag) values(UUID(),'" + user_id + "','" + email_plan_id + "','" + email_plan_desc + "','" + email_send_time + "','" + deal_flag + "')", "dataSource");
                            log.debug("2-知悉并跟进-处理结果:" + mailresult);

                            deal_code = 1;
                            deal_msg = "知悉并跟进-处理完成";

                        }

                    } catch (Exception e) {
                        log.error("[" + i + "]" + "接口处理异常" + e.getMessage());

                        deal_code = -1;
                        deal_msg = "处理异常：" + e.getMessage();

                    } finally {
                        JSONObject tempJsonP = new JSONObject();
                        tempJsonP.put("user_id", user_id);
                        tempJsonP.put("email_plan_id", email_plan_id);
                        tempJsonP.put("deal_code", deal_code);
                        tempJsonP.put("deal_msg", deal_msg);
                        log.debug("[" + i + "]" + "当前处理数据结果：" + inJsonDataP.toString());

                        resultArr.add(tempJsonP);
                    }

                }

                // 将本次调用的批次涉及知悉并跟进发送坐席
                sendBatchMSG(eliteBean, Batch_Id, "2");

                // 将本次调用的批次涉及知悉发送坐席(排查同用户同邮件知悉并跟进)
                sendBatchMSG(eliteBean, Batch_Id, "1");

                result.put("code", 1);
                result.put("msg", "SUCC");
                result.put("data", resultArr);
            } catch (Exception e) {
                log.error("知决邮件发送结果处理异常-", e);
                result.put("code", -1);
                result.put("msg", "数据处理错误:" + e.getMessage());
                result.put("data", resultArr);
            }

        }

        log.debug("知决邮件发送结果通知处理结果：" + result.toString());
        return result.toString();
    }

    public static boolean sendMsg_Note(EliteBean eliteBean, String Subject, String Content, String Staffid, String StaffName, String Priority) {

        String note_Guid = KHUtil.getRandomString(36);
        String Msg_Note_Staff = "Insert Into Msg_Note_Staff (Msgid, Staffid, Readtime, Flag, Replied, Deleted) Values ('" + note_Guid + "', '" + Staffid + "', Null, 0, 0, 0)";
        String Msg_Note = "Insert Into Msg_Note (Id, Subject, Priority, Receiver, Createdby, Createdtime, Deleted, Content) Values ('" + note_Guid + "', '" + Subject + "', '" + Priority + "', '" + StaffName + "', 'SELITE', Now(), 0, '" + Content + "</br></br><span style=\"color:red\">⚠️本便签由系统自动发出，请勿直接回复！</span>')";
        eliteBean.update(Msg_Note_Staff, "dataSource");
        eliteBean.update(Msg_Note, "dataSource");

    }

    public static boolean sendBatchMSG(EliteBean eliteBean, String Batch_ID, String deal_Type) {
        String runSQL = deal_Type == "2" ? '''Select R1.User_Id,
       R1.Email_Plan_Desc,
       s.Staff_Id,
       s.StaffName,
       s.Defaultrolegroup,
       c.Customername,
       Min(Date_Format(R1.Email_Send_Time, '%Y-%m-%d %H:%i:%s')) As Email_Send_Time,
       c.Customer_Guid,
       c.Customer_Id
  From Hst_Mailresult_Log R1
  Left Join Customer c
    On R1.User_Id = c.Stringfield102
  Left Join Objective o
    On c.Customer_Guid = o.Customer_Guid
  Left Join Staff s
    On s.Staff_Id = o.Handleby_Id
 Where R1.Batch_Id = \'''' + Batch_ID + '''\'
   And R1.Deal_Flag = 2
   And o.Map_Id = 'MY48ZX'
   And s.Workstatus = 'ONLINE'
 Group By R1.User_Id,
          R1.Email_Plan_Desc,
          s.Staff_Id,
          s.Staffname,
          s.Defaultrolegroup,
          c.Customername,
          c.Customer_Guid,
          c.Customer_Id
 Order By s.Staff_Id, s.Defaultrolegroup, Email_Send_Time''' : '''Select R1.User_Id,
       R1.Email_Plan_Desc,
       s.Staff_Id,
       s.StaffName,
       s.Defaultrolegroup,
       c.Customername,
       Min(Date_Format(R1.Email_Send_Time, '%Y-%m-%d %H:%i:%s')) As Email_Send_Time,
       c.Customer_Guid,
       c.Customer_Id
  From Hst_Mailresult_Log R1
  Left Join Hst_Mailresult_Log R2
    On R1.User_Id = R2.User_Id
   And R1.Email_Plan_Desc = R2.Email_Plan_Desc
   And R2.Batch_Id = \'''' + Batch_ID + '''\'
   And R2.Deal_Flag = 2
  Left Join Customer c
    On R1.User_Id = c.Stringfield102
  Left Join Objective o
    On c.Customer_Guid = o.Customer_Guid
  Left Join Staff s
    On s.Staff_Id = o.Handleby_Id
 Where R1.Batch_Id = \'''' + Batch_ID + '''\'
   And R1.Deal_Flag = 1
   And R2.Mailresultguid Is Null
   And o.Map_Id = 'MY48ZX'
   And s.Workstatus = 'ONLINE'
 Group By R1.User_Id,
          R1.Email_Plan_Desc,
          s.Staff_Id,
          s.Staffname,
          s.Defaultrolegroup,
          c.Customername,
          c.Customer_Guid,
          c.Customer_Id
 Order By s.Staff_Id, s.Defaultrolegroup, Email_Send_Time''';

        List runSQLList = eliteBean.chaxun_sql(runSQL, "dataSource");

        String o_Staff_Id = "";
        String o_Staffname = "";
        String o_Rolegroup_Id = "";
        String noticeContext = "";
        for (int i = 0; i < runSQLList.size(); i++) {
            String Staff_Id = runSQLList.get(i).get("Staff_Id");
            String Staffname = runSQLList.get(i).get("StaffName");
            String Rolegroup_Id = runSQLList.get(i).get("Defaultrolegroup");
            String Customer_Id = runSQLList.get(i).get("Customer_Id");
            String Customername = runSQLList.get(i).get("Customername");
            String User_Id = runSQLList.get(i).get("User_Id");
            String Email_Plan_Desc = runSQLList.get(i).get("Email_Plan_Desc");
            String Email_Send_Time = runSQLList.get(i).get("Email_Send_Time");
            log.debug("[" + i + "]" + "当前处理信息：" + runSQLList.get(i).toString());

            // 如果当前数据对应的对分对象已经变了 在开始对上一个对象进行计算分数
            o_Staff_Id = KHUtil.isNull(o_Staff_Id) ? Staff_Id : o_Staff_Id;
            o_Staffname = KHUtil.isNull(o_Staff_Id) ? Staffname : o_Staffname;
            o_Rolegroup_Id = KHUtil.isNull(o_Rolegroup_Id) ? Rolegroup_Id : o_Rolegroup_Id;

            // 如果当前数据对应的对分对象已经变了 在开始对上一个对象进行计算分数
            if (o_Staff_Id != Staff_Id || o_Rolegroup_Id != Rolegroup_Id) {
                sendMsg_Note(eliteBean, "客户接收邮件通知" + (deal_Type == "2" ? "⚠" : ""), noticeContext, o_Staff_Id, o_Staffname, deal_Type == "2" ? "1" : "0");
                int mailresult = eliteBean.update("Insert Into Hst_Leadsnotice (Noticeid, Noticegroup, Noticeby, Creategroup, Createby, Noticecontent, Createddate, Limitcount, Loadcount, Noticetype, Email_Plan_Id) Values (Uuid(), '" + o_Rolegroup_Id + "', '" + o_Staff_Id + "', 'SYSTEM', 'SELITE', '" + noticeContext + "', Now(), 1, 0, '13', '" + Batch_ID + "')", "dataSource");
                log.debug("[" + i + "]" + "推送邮件活动提醒跟进 结果:" + mailresult);

                // 把最新取到的数据放入str
                noticeContext = "";
                noticeContext = noticeContext + "</br>" + "📌客户:" + Customername + (KHUtil.isNull(Customer_Id) ? " 用户ID:" + User_Id : " 华盛号:" + Customer_Id) + " 于" + Email_Send_Time + " 收到系统计划邮件【" + Email_Plan_Desc + "】";
                o_Staff_Id = Staff_Id;
                o_Staffname = Staffname;
                o_Rolegroup_Id = Rolegroup_Id;

            } else {
                noticeContext = noticeContext + "</br>" + "📌客户:" + Customername + (KHUtil.isNull(Customer_Id) ? " 用户ID:" + User_Id : " 华盛号:" + Customer_Id) + " 于" + Email_Send_Time + " 收到系统计划邮件【" + Email_Plan_Desc + "】";
            }

        }
        sendMsg_Note(eliteBean, "客户接收邮件通知" + (deal_Type == "2" ? "⚠" : ""), noticeContext, o_Staff_Id, o_Staffname, deal_Type == "2" ? "1" : "0");
        int mailresult = eliteBean.update("Insert Into Hst_Leadsnotice (Noticeid, Noticegroup, Noticeby, Creategroup, Createby, Noticecontent, Createddate, Limitcount, Loadcount, Noticetype, Email_Plan_Id) Values (Uuid(), '" + o_Rolegroup_Id + "', '" + o_Staff_Id + "', 'SYSTEM', 'SELITE', '" + noticeContext + "', Now(), 1, 0, '13', '" + Batch_ID + "')", "dataSource");
        log.debug("[End]" + "推送邮件活动提醒跟进 结果:" + mailresult);

    }
}